<template>
  <div class="repair-record-page">
    <div class="page-header">
      <h2>设备维修记录管理</h2>
      <p>管理系统中的设备维修记录</p>
    </div>

    <div class="operation-section">
      <el-card class="search-card">
        <div class="search-header">
          <h3>搜索条件</h3>
          <el-button type="info" plain @click="handleReset">重置</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchForm.keyword"
              placeholder="设备名称/编码"
              clearable
              prefix-icon="Search"
            />
          </el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" class="search-btn" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
          </el-col>
        </el-row>
      </el-card>

      <div class="toolbar">
        <el-button type="primary" class="toolbar-btn" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增维修记录
        </el-button>
        <el-button class="toolbar-btn" @click="loadRepairRecordList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        class="record-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          prop="deviceName"
          label="设备名称"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-link type="primary" @click="handleView(scope.row)">
              {{ scope.row.deviceName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="deviceCode" label="设备编码" min-width="120" />
        <el-table-column
          prop="repairProject"
          label="维修项目"
          min-width="120"
        />
        <el-table-column prop="repairer" label="维修人" width="100" />
        <el-table-column
          prop="repairTime"
          label="维修时间"
          width="160"
          align="center"
        />
        <el-table-column prop="repairHours" label="维修工时" width="100" />
        <el-table-column
          prop="repairCost"
          label="维修费用(元)"
          width="120"
          align="right"
        />
        <el-table-column prop="processingStatus" label="处理情况" width="120" />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
              <el-button
                size="small"
                type="warning"
                link
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                link
                @click="handleDeleteWithCheck(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
      class="record-dialog"
    >
      <el-form
        ref="formRef"
        :model="recordForm"
        :rules="formRules"
        label-width="120px"
        class="record-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备ID" prop="equipmentId">
              <el-input
                v-model.number="recordForm.equipmentId"
                placeholder="请输入设备ID"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修项目" prop="repairProject">
              <el-input
                v-model="recordForm.repairProject"
                placeholder="请输入维修项目"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维修人" prop="repairer">
              <el-input
                v-model="recordForm.repairer"
                placeholder="请输入维修人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修时间" prop="repairTime">
              <el-date-picker
                v-model="recordForm.repairTime"
                type="datetime"
                placeholder="请选择维修时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维修工时" prop="repairHours">
              <el-input
                v-model.number="recordForm.repairHours"
                placeholder="请输入维修工时"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修费用(元)" prop="repairCost">
              <el-input
                v-model.number="recordForm.repairCost"
                placeholder="请输入维修费用"
                type="number"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="故障详情" prop="faultDetails">
          <el-input
            v-model="recordForm.faultDetails"
            type="textarea"
            :rows="3"
            placeholder="请输入故障详情"
          />
        </el-form-item>

        <el-form-item label="处理情况" prop="processingStatus">
          <el-input
            v-model="recordForm.processingStatus"
            type="textarea"
            :rows="3"
            placeholder="请输入处理情况"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="viewDialogVisible"
      title="维修记录详情"
      width="60%"
      class="view-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备ID">
          {{ viewRecord.equipmentId }}
        </el-descriptions-item>
        <el-descriptions-item label="维修项目">
          {{ viewRecord.repairProject }}
        </el-descriptions-item>
        <el-descriptions-item label="维修人">
          {{ viewRecord.repairer }}
        </el-descriptions-item>
        <el-descriptions-item label="维修时间">
          {{ formatDate(viewRecord.repairTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="维修工时">
          {{ viewRecord.repairHours }}
        </el-descriptions-item>
        <el-descriptions-item label="维修费用(元)">
          {{ viewRecord.repairCost }}
        </el-descriptions-item>
        <el-descriptions-item label="维修单号">
          {{ viewRecord.repairOrderNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="维修次数">
          {{ viewRecord.repairCount }}
        </el-descriptions-item>
        <el-descriptions-item label="故障详情" :span="2">
          {{ viewRecord.faultDetails }}
        </el-descriptions-item>
        <el-descriptions-item label="处理情况" :span="2">
          {{ viewRecord.processingStatus }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Refresh } from "@element-plus/icons-vue";
import moment from "moment";
import type {
  RepairRecord,
  RepairRecordVo,
  RepairRecordQuery,
  RepairRecordAdd,
  RepairRecordUpdate
} from "@/api/repairRecord";
import {
  getRepairRecordList,
  getRepairRecordDetail,
  addRepairRecord,
  updateRepairRecord,
  deleteRepairRecord
} from "@/api/repairRecord";

defineOptions({ name: "RepairRecord" });

const loading = ref(false);
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const dialogTitle = ref("新增维修记录");
const formRef = ref();
const submitLoading = ref(false);
const multipleSelection = ref<RepairRecordVo[]>([]);

const searchForm = reactive<RepairRecordQuery>({
  page: 1,
  limit: 10,
  keyword: "",
  dateRange: []
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const tableData = ref<RepairRecordVo[]>([]);

const recordForm = reactive<RepairRecord>({
  equipmentId: undefined,
  repairProject: "",
  repairer: "",
  repairTime: "",
  repairHours: 0,
  repairCost: undefined,
  faultDetails: "",
  processingStatus: ""
});

const viewRecord = reactive<RepairRecord>({
  equipmentId: undefined,
  repairProject: "",
  repairer: "",
  repairTime: "",
  repairHours: 0,
  repairCost: undefined,
  faultDetails: "",
  processingStatus: ""
});

const formRules = reactive({
  equipmentId: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
  repairProject: [
    { required: true, message: "请输入维修项目", trigger: "blur" }
  ],
  repairer: [{ required: true, message: "请输入维修人", trigger: "blur" }],
  repairTime: [
    { required: true, message: "请选择维修时间", trigger: "change" }
  ],
  repairHours: [{ required: true, message: "请输入维修工时", trigger: "blur" }],
  repairCost: [{ required: true, message: "请输入维修费用", trigger: "blur" }]
});

const formatDate = (date: string) => {
  if (!date) return "";
  return moment(date).format("YYYY-MM-DD HH:mm:ss");
};

onMounted(() => {
  loadRepairRecordList();
});

const loadRepairRecordList = async () => {
  loading.value = true;
  try {
    const params: RepairRecordQuery = {
      ...searchForm,
      page: pagination.currentPage,
      limit: pagination.pageSize
    };
    const res = await getRepairRecordList(params);
    if (res.code === 0 && res.data) {
      tableData.value = res.data.list || [];
      pagination.total = res.data.total || 0;
    } else {
      ElMessage.error(res.message || "获取维修记录列表失败");
    }
  } catch (error) {
    console.error("获取维修记录列表失败:", error);
    ElMessage.error("获取维修记录列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.currentPage = 1;
  loadRepairRecordList();
};

const handleReset = () => {
  searchForm.keyword = "";
  searchForm.dateRange = [];
  handleSearch();
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  loadRepairRecordList();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  loadRepairRecordList();
};

const handleSelectionChange = (val: RepairRecordVo[]) => {
  multipleSelection.value = val;
};

const showAddDialog = () => {
  dialogTitle.value = "新增维修记录";
  dialogVisible.value = true;
  resetForm();
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(recordForm, {
    equipmentId: undefined,
    repairProject: "",
    repairer: "",
    repairTime: "",
    repairHours: 0,
    repairCost: undefined,
    faultDetails: "",
    processingStatus: ""
  });
};

const handleView = async (row: RepairRecordVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的维修记录ID");
    return;
  }

  try {
    const response = await getRepairRecordDetail(Number(row.id));
    if (response.code === 0 && response.data) {
      Object.assign(viewRecord, response.data);
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取维修记录详情失败");
    }
  } catch (error) {
    console.error("获取维修记录详情异常:", error);
    ElMessage.error("获取维修记录详情失败");
  }
};

const handleEdit = async (row: RepairRecordVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的维修记录ID");
    return;
  }

  try {
    const response = await getRepairRecordDetail(Number(row.id));
    if (response.code === 0 && response.data) {
      Object.assign(recordForm, response.data);
      dialogTitle.value = "编辑维修记录";
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取维修记录详情失败");
    }
  } catch (error) {
    console.error("获取维修记录详情异常:", error);
    ElMessage.error("获取维修记录详情失败");
  }
};

const handleDeleteWithCheck = (row: RepairRecordVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的维修记录ID");
    return;
  }

  handleDelete(Number(row.id));
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定要删除该维修记录吗？删除后无法恢复。", "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteRepairRecord(id);
        if (response.code === 0) {
          ElMessage.success("删除成功");
          loadRepairRecordList();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除维修记录异常:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        let response;
        if (dialogTitle.value === "新增维修记录") {
          const addData: RepairRecordAdd = {
            equipmentId: recordForm.equipmentId!,
            repairProject: recordForm.repairProject,
            repairer: recordForm.repairer,
            repairTime: recordForm.repairTime
              ? moment(recordForm.repairTime).format("YYYY-MM-DD HH:mm:ss")
              : "",
            repairHours: recordForm.repairHours!,
            repairCost: recordForm.repairCost!,
            faultDetails: recordForm.faultDetails,
            processingStatus: recordForm.processingStatus
          };
          response = await addRepairRecord(addData);
        } else {
          const updateData: RepairRecordUpdate = {
            id: recordForm.id!,
            equipmentId: recordForm.equipmentId!,
            repairProject: recordForm.repairProject,
            repairer: recordForm.repairer,
            repairTime: recordForm.repairTime
              ? moment(recordForm.repairTime).format("YYYY-MM-DD HH:mm:ss")
              : "",
            repairHours: recordForm.repairHours!,
            repairCost: recordForm.repairCost!,
            faultDetails: recordForm.faultDetails,
            processingStatus: recordForm.processingStatus
          };
          response = await updateRepairRecord(updateData);
        }

        if (response.code === 0) {
          ElMessage.success(
            dialogTitle.value === "新增维修记录" ? "新增成功" : "更新成功"
          );
          dialogVisible.value = false;
          loadRepairRecordList();
        } else {
          ElMessage.error(
            response.message ||
              (dialogTitle.value === "新增维修记录" ? "新增失败" : "更新失败")
          );
        }
      } catch (error) {
        console.error(
          dialogTitle.value === "新增维修记录"
            ? "新增维修记录异常:"
            : "更新维修记录异常:",
          error
        );
        ElMessage.error(
          dialogTitle.value === "新增维修记录" ? "新增失败" : "更新失败"
        );
      } finally {
        submitLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.repair-record-page {
  padding: 20px;
  background-color: #f5f6f7;
  min-height: calc(100vh - 80px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #606266;
}

.operation-section {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 16px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-header h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-row) .el-col {
  margin-bottom: 16px;
}

.search-btn {
  width: 100%;
  height: 32px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-btn {
  height: 36px;
}

.table-card {
  margin-bottom: 20px;
}

.record-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.record-table :deep(.el-table__row:hover) {
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 0;
}

.record-dialog :deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

.record-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.view-dialog :deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
}

@media (max-width: 768px) {
  .repair-record-page {
    padding: 12px;
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style>
